﻿// cmdAddNewLayerCommand.cpp
//

#include "stdafx.h"


////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
//
// BEGIN AddNewLayerCommand command
//

#pragma region AddNewLayerCommand command

class CCommandAddNewLayerCommand : public CRhinoCommand
{
public:
	CCommandAddNewLayerCommand() = default;
	UUID CommandUUID() override
	{
		// {53e81643-3c83-4e81-82c7-95adc6ae724b}
		static const GUID AddNewLayerCommandCommand_UUID =
		{0x53e81643,0x3c83,0x4e81,{0x82,0xc7,0x95,0xad,0xc6,0xae,0x72,0x4b}};
		return AddNewLayerCommandCommand_UUID;
	}
	const wchar_t* EnglishCommandName() override { return L"AddNewLayer"; }
	CRhinoCommand::result RunCommand(const CRhinoCommandContext& context) override;
};

// The one and only CCommandAddNewLayerCommand object
static class CCommandAddNewLayerCommand theAddNewLayerCommandCommand;

CRhinoCommand::result CCommandAddNewLayerCommand::RunCommand(const CRhinoCommandContext& context)
{
	// Get reference to the document's layer table
	CRhinoLayerTable& layer_table = context.m_doc.m_layer_table;
	// Cook up an unused layer name
	ON_wString unused_name;
	layer_table.GetUnusedLayerName(unused_name);

	// Prompt the user to enter a layer name
	CRhinoGetString gs;
	gs.SetCommandPrompt(L"Name of layer to add");
	gs.SetDefaultString(unused_name);
	gs.AcceptNothing(TRUE);
	gs.GetString();
	if (gs.CommandResult() != CRhinoCommand::success)
		return gs.CommandResult();

	// Was a layer named entered?
	ON_wString layer_name = gs.String();
	layer_name.TrimLeftAndRight();
	if (layer_name.IsEmpty())
	{
		RhinoApp().Print(L"Layer name cannot be blank.\n");
		return CRhinoCommand::cancel;
	}

	// Is the layer name valid?
	if (!RhinoIsValidName(layer_name))
	{
		RhinoApp().Print(L"\"%s\" is not a valid layer name.\n", layer_name);
		return CRhinoCommand::cancel;
	}

	// Does a layer with the same name already exist?
	int layer_index =layer_table.FindLayerFromUniqueName(layer_name);
	if (layer_index >= 0)
	{
		RhinoApp().Print(L"A layer with the name \"%s\" already exists.\n", layer_name);
		return CRhinoCommand::cancel;
	}

	// Create a new layer
	ON_Layer layer;
	layer.SetName(layer_name);
	// Add the layer to the layer table
	layer_index = layer_table.AddLayer(layer);
	if (layer_index < 0)
	{
		RhinoApp().Print(L"Unable to add \"%s\" layer.\n", layer_name);
		return CRhinoCommand::failure;
	}
	return CRhinoCommand::success;
}

#pragma endregion

//
// END AddNewLayerCommand command
//
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
